<template>
  <div class="register-page">
    <div class="register-box">
      <div class="head-box">假接口</div>
      <el-form
        ref="regFormRef"
        :model="regForm"
        :rules="regRules"
        class="core-box"
        auto-complete="on"
        label-position="left"
      >
        <div class="title-container">
          <h3 class="title">注册</h3>
        </div>

        <el-form-item prop="yhm">
          <el-input
            :prefix-icon="User"
            v-model="regForm.yhm"
            placeholder="请输入真实姓名"
            name="yhm"
            type="text"
            tabindex="1"
            auto-complete="on"
            clearable
          />
        </el-form-item>

        <el-form-item prop="sjh">
          <el-input
            :prefix-icon="Iphone"
            v-model="regForm.sjh"
            placeholder="请输入手机号"
            name="sjh"
            type="text"
            tabindex="1"
            auto-complete="on"
            clearable
          />
        </el-form-item>

        <el-form-item prop="mm">
          <el-input
            :prefix-icon="Lock"
            v-model="regForm.mm"
            type="text"
            placeholder="请输入密码，字母、数字组合至少8位"
            name="mm"
            tabindex="2"
            auto-complete="on"
            clearable
            show-password
          />
        </el-form-item>

        <el-form-item prop="xmm">
          <el-input
            :prefix-icon="Lock"
            v-model="regForm.xmm"
            type="text"
            placeholder="请再次输入密码"
            name="xmm"
            tabindex="2"
            auto-complete="on"
            clearable
            show-password
          />
        </el-form-item>

        <el-form-item prop="code">
          <el-input
            v-model="regForm.code"
            auto-complete="off"
            placeholder="请输入验证码"
            style="width: 65%"
            clearable
          >
            <template #prefix>
              <img :src="iconPic.yzm" />
            </template>
          </el-input>

          <div class="captcha">
            <img :src="codeImgUrl" @click="handleCaptchaGenerate" />
          </div>
        </el-form-item>
        <el-form-item prop="verification_code">
          <el-input
            :prefix-icon="ChatDotSquare"
            v-model="regForm.verification_code"
            maxlength="4"
            placeholder="请输入短信验证码"
          >
            <template #suffix>
              <div>
                <div v-if="counter > 0" class="daojishi">{{ countdownText }}</div>
                <div v-else @click="sendSmsCode" class="huoqu">获取验证码</div>
              </div>
            </template>
          </el-input>
        </el-form-item>

        <div class="anniu" @click.prevent="handleReg">立即注册</div>
        <div class="other" @click="goLogin">已有账号？去登录</div>
        <div class="xieyi">
          <span>注册即代表同意</span>
          <span class="gen" @click="goAgreement">《用户隐私协议》</span>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElInput, ElMessage } from 'element-plus';
import { User, Iphone, Lock, ChatDotSquare } from '@element-plus/icons-vue';
import router from '@/router';

import { getCaptcha, sendCode, regAdd } from '@/api/logreg';
import { RegisterForm, CodeQuery } from '@/api/logreg/types';

const regFormRef = ref(ElForm);

const state = reactive({
  regForm: {} as RegisterForm,
  regRules: {
    yhm: [{ required: true, message: '真实姓名不能为空', trigger: 'blur' }],
    sjh: [
      { required: true, message: '手机号不能为空', trigger: 'blur' },
      { min: 11, max: 11, message: '请输入11位的手机号', trigger: 'blur' }
    ],
    mm: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
        message: '密码须为8~20位数字和字母组合',
        trigger: 'blur'
      }
    ],
    xmm: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
        message: '密码须为8~20位数字和字母组合',
        trigger: 'blur'
      }
    ],
    code: [{ required: true, message: '验证码不能为空', trigger: 'blur' }],
    verification_code: [{ required: true, message: '短信验证码不能为空', trigger: 'blur' }]
  },
  codeImgUrl: '',
  counter: 0, // 计数器
  countdownText: '', // 倒计时文本
  timer: '' as any, // 计时器对象
  throttle: true,

  iconPic: {
    yzm: new URL('/src/assets/img/login/yzm.png', import.meta.url).href
  }
});

const { regForm, regRules, codeImgUrl, counter, countdownText, iconPic } = toRefs(state);

/**
 *  注册处理
 */
function handleReg() {
  regFormRef.value.validate((valid: boolean) => {
    if (valid) {
      let { yhm, sjh, mm, xmm, verification_code, verification_key } = state.regForm;
      if (mm != xmm) {
        ElMessage.warning('密码不一致');
        return;
      }
      if (state.throttle) {
        state.throttle = false;
        let data = { yhm, sjh, mm, verification_code, verification_key };
        regAdd(data)
          .then(() => {
            router.push('/login');
            state.throttle = true;
          })
          .catch(() => {
            state.throttle = true;
            handleCaptchaGenerate();
          });
      }
    } else {
      return false;
    }
  });
}

// 获取验证码
function handleCaptchaGenerate() {
  getCaptcha().then(({ data }) => {
    const { img, key } = data;
    state.codeImgUrl = img;
    state.regForm.key = key;
  });
}

// 获取短信验证码
function sendSmsCode() {
  regFormRef.value.validateField(['sjh', 'code'], (valid: boolean) => {
    if (valid) {
      let { sjh, code, key } = state.regForm;
      let datas = { sjh, code, key } as CodeQuery;
      sendCode(datas)
        .then((res: any) => {
          countdown();
          state.regForm.verification_key = res.data.key;
        })
        .catch(() => {
          handleCaptchaGenerate();
        });
    }
  });
}

// 倒计时
function countdown() {
  state.counter = 30;
  state.countdownText = state.counter + 's';
  state.timer = setInterval(() => {
    state.counter--;
    state.countdownText = state.counter + 's';
    if (state.counter < 0) {
      clearInterval(state.timer);
    }
  }, 1000);
}

// 跳转到登录页
function goLogin() {
  router.push('/login');
}
// 跳转到用户隐私协议
function goAgreement() {
  console.log('跳转到用户隐私协议');
}

onMounted(() => {
  handleCaptchaGenerate();
});
onUnmounted(() => {
  if (null != state.timer) {
    clearInterval(state.timer); // 销毁
    state.timer = null;
  }
});
</script>

<style lang="scss" scoped>
.register-page {
  background: url('../../assets/img/login/bg.png') no-repeat;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  background-size: cover;
}
.register-box {
  margin-left: 60%;
  height: 650px;
  width: 512px;
  background-color: #fff;
  overflow: hidden;
  @media (max-width: 2560px) {
    margin-top: 10%;
  }
  @media (max-width: 1920px) {
    margin-top: 5%;
  }

  .head-box {
    text-align: center;
    margin-top: 50px;
    font-size: 28px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #4a7bfe;
  }

  .core-box {
    position: relative;
    width: 320px;
    max-width: 100%;
    padding: 30px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 20px;
      color: #333333;
      margin: 0px auto 30px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .daojishi {
    font-size: 16px;
    color: #658fff;
  }
  .huoqu {
    font-size: 14px;
    font-family: Source Han Sans SC;
    font-weight: 400;
    color: #658fff;
    cursor: pointer;
  }

  .anniu {
    @include twoAlign(320, 40);
    background: #658fff;
    border-radius: 4px;
    font-size: 16px;
    font-family: SourceHanSansSC;
    font-weight: 400;
    color: #ffffff;
    cursor: pointer;
    margin-top: 40px;
    margin-bottom: 12px;
  }

  .other {
    text-align: center;
    font-size: 14px;
    font-family: SourceHanSansSC;
    font-weight: 400;
    color: #658fff;
    cursor: pointer;
    margin-bottom: 30px;
  }

  .xieyi {
    text-align: center;
    font-size: 14px;
    font-family: SourceHanSansSC;
    font-weight: 400;
    color: #999999;
    margin-bottom: 26px;
    .gen {
      color: #658fff;
      cursor: pointer;
    }
  }

  .captcha {
    position: absolute;
    right: 0;
    top: 0;

    img {
      height: 32px;
      cursor: pointer;
      vertical-align: middle;
    }
  }
}
</style>
